package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.CustomerRequirementRecord;
import com.ruoyi.system.mapper.CustomerRequirementRecordMapper;
import com.ruoyi.system.service.ICustomerRequirementRecordService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CustomerRequirementRecordServiceImpl implements ICustomerRequirementRecordService {

    @Resource
    private CustomerRequirementRecordMapper recordMapper;

    @Override
    public void saveOrUpdateRecords(Long projectId, String projectNo, Long designerId, String designerName, List<CustomerRequirementRecord> records) {
        if (records == null || records.isEmpty()) {
            return;
        }
        for (CustomerRequirementRecord record : records) {
            record.setProjectId(projectId);
            record.setProjectNo(projectNo);
            record.setDesignerId(designerId);
            record.setDesignerName(designerName);

            // upsert by unique key (project_id + template_item_code)
            CustomerRequirementRecord exist = recordMapper.selectOne(Wrappers.<CustomerRequirementRecord>lambdaQuery()
                    .eq(CustomerRequirementRecord::getProjectId, projectId)
                    .eq(CustomerRequirementRecord::getTemplateItemCode, record.getTemplateItemCode())
                    .last("limit 1"));
            if (exist == null) {
                recordMapper.insert(record);
            } else {
                record.setId(exist.getId());
                recordMapper.updateById(record);
            }
        }
    }

    @Override
    public List<CustomerRequirementRecord> listByProjectId(Long projectId) {
        return recordMapper.selectList(new LambdaQueryWrapper<CustomerRequirementRecord>()
                .eq(CustomerRequirementRecord::getProjectId, projectId)
                .eq(CustomerRequirementRecord::getDeleted, 0));
    }
}


